//
//  HomeManageViewController.m
//  location
//
//  Created by Dongxiang Xu on 2025/5/6.
//

#import "HomeManageViewController.h"
#import "HomeDetailViewController.h"
#import "AddHomeSheetView.h"

@interface HomeManageViewController ()

@property (nonatomic,strong) UIScrollView *scrollView;
@property (nonatomic,strong) UIView *infoView;
@property (nonatomic,strong) NSMutableArray *array;

@end

@implementation HomeManageViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    self.view.backgroundColor = WhiteColor;
    
    UIButton *add = [[UIButton alloc] initWithFrame:CGRectMake(16, SCREEN_HEIGHT-100, SCREEN_WIDTH-32, 60)];
    add.backgroundColor = RealBlackColor;
    add.layer.masksToBounds = YES;
    [add.layer setCornerRadius:20];
    [add setImage:[UIImage imageNamed:@"add_new_home"] forState:UIControlStateNormal];
    [add setTitle:@" 新建家庭" forState:UIControlStateNormal];
    [add setTitleColor:RealWhiteColor forState:UIControlStateNormal];
    [add.titleLabel setFont:REAL_MEDIUM_FONT(15)];
    add.contentHorizontalAlignment = UIControlContentHorizontalAlignmentCenter;
    [[add rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
        if (self.array.count<5) {
            BOOL isAdd = NO;
            for (UIView *view in self.view.subviews) {
                if ([view isKindOfClass:[AddHomeSheetView class]]) {
                    isAdd = YES;
                }
            }
            if (isAdd==NO) {
                AddHomeSheetView *view = [[AddHomeSheetView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT)];
                [self.view addSubview:view];
                view.AddHomeBlock = ^(NSString *groupId) {
                    [self getGroupList];
                };
            }
        }else{
            UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"最多创建 5 个家庭" message:nil preferredStyle:UIAlertControllerStyleAlert];
            UIAlertAction *action = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:nil];
            [alertController addAction:action];
            [self presentViewController:alertController animated:YES completion:nil];
        }
    }];
    [self.view addSubview:add];
    
    _scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, NAVHEIGHT, SCREEN_WIDTH, SCREEN_HEIGHT-NAVHEIGHT-110)];
    _scrollView.showsVerticalScrollIndicator = NO;
    _scrollView.showsHorizontalScrollIndicator = NO;
    _scrollView.alwaysBounceVertical = YES;
    if (@available(iOS 11.0, *)) {
        _scrollView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    }
    [self.view addSubview:_scrollView];
    
    UILabel *title = [[UILabel alloc] initWithFrame:CGRectMake(16, 6, SCREEN_WIDTH-32, 32)];
    title.font = REAL_MEDIUM_FONT(24);
    title.text = @"家庭管理";
    title.textColor = RealBlackColor;
    [self.scrollView addSubview:title];
    
    _infoView = [[UIView alloc] initWithFrame:CGRectMake(16, CGRectGetMaxY(title.frame)+14, SCREEN_WIDTH-32, 62)];
    _infoView.layer.masksToBounds = YES;
    [_infoView.layer setCornerRadius:16];
    _infoView.backgroundColor = RealWhiteColor;
    [self.scrollView addSubview:_infoView];
    
    // 获取Documents目录路径
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *plistPath = [documentsDirectory stringByAppendingPathComponent:@"GroupList.plist"];
    
    // 检查文件是否存在
    if ([[NSFileManager defaultManager] fileExistsAtPath:plistPath]) {
        // 从plist文件读取数据
        NSArray *loadedArray = [NSArray arrayWithContentsOfFile:plistPath];
        if (loadedArray) {
            self.array = [NSMutableArray arrayWithArray:loadedArray];
            [self initView];            
        }
    }
    
      
    [self getGroupList];
}

- (void)getGroupList
{  
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    CryptoHTTPKit *manager = [[CryptoHTTPKit alloc] init];
    [manager encryptedPOST:@"/system/group/grouplist"
    parameters:param
    success:^(NSDictionary *responseObject) {
        if ([responseObject[@"code"] integerValue]==200 && [responseObject[@"data"] isKindOfClass:[NSArray class]]) {
            self.array = [NSMutableArray arrayWithArray:responseObject[@"data"]];
            [self initView];
        }
    }
    failure:^(NSError *aError) {
       
    }];
}

- (void)initView
{
    for (UIView *view in _infoView.subviews) {
        [view removeFromSuperview];
    }
    _infoView.height = 62*_array.count;
    [_scrollView setContentSize:CGSizeMake(0, CGRectGetMaxY(_infoView.frame)+10)];
    for (int i = 0; i<_array.count; i ++) {
        UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(0, i*62, _infoView.width, 62)];
        [_infoView addSubview:button];
        
        UILabel *name = [[UILabel alloc] initWithFrame:CGRectMake(16, 10, button.width-56, 22)];
        name.text = _array[i][@"name"];
        name.textColor = RealBlackColor;
        name.font = REAL_MEDIUM_FONT(15);
        [button addSubview:name];
        
        UILabel *count = [[UILabel alloc] initWithFrame:CGRectMake(name.x, CGRectGetMaxY(name.frame), name.width, 20)];
        count.text = [NSString stringWithFormat:@"%@名成员",_array[i][@"memberCount"]];
        count.textColor = GraryTooHeavyColor;
        count.font = DEFAULT_FONT(12);
        [button addSubview:count];
                
        if ([_array[i][@"membership"] isKindOfClass:[NSDictionary class]]) {
            count.text =  [count.text stringByAppendingString:@" |"];
            [count sizeToFit];
            [count setFrame:CGRectMake(name.x, CGRectGetMaxY(name.frame), count.width, 20)];
            
            UIImageView *memberIcon = [[UIImageView alloc] initWithFrame:CGRectMake(count.maxX, CGRectGetMaxY(name.frame), 20, 20)];
            [button addSubview:memberIcon];
            
            UILabel *member = [[UILabel alloc] initWithFrame:CGRectMake(memberIcon.maxX+2, CGRectGetMaxY(name.frame), 50, 20)];
            member.font = DEFAULT_FONT(12);
            member.textColor = GraryTooHeavyColor;
            [button addSubview:member];
            if ([_array[i][@"membership"][@"planType"] integerValue]==1) {
                memberIcon.image = [UIImage imageNamed:@"icon_close"];
                member.text = @"亲密会员";
            }else if ([_array[i][@"membership"][@"planType"] integerValue]==2) {
                memberIcon.image = [UIImage imageNamed:@"icon_silver"];
                member.text = @"白银会员";
            }else if ([_array[i][@"membership"][@"planType"] integerValue]==3) {
                memberIcon.image = [UIImage imageNamed:@"icon_gold"];
                member.text = @"黄金会员";
            }
        }
        
        
        UIImageView *arrow = [[UIImageView alloc] initWithFrame:CGRectMake(button.width-28, (button.height-12)/2, 12, 12)];
        arrow.image = [UIImage imageNamed:@"arrow_right"];
        [button addSubview:arrow];
        
        UIImageView *line = [[UIImageView alloc] initWithFrame:CGRectMake(name.x, button.height-1, button.width-2*name.x, 1)];
        line.image = [UIImage imageNamed:@"line"];
        [button addSubview:line];
        
        [[button rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
            HomeDetailViewController *vc = [[HomeDetailViewController alloc] init];
            vc.groupId = self.array[i][@"id"];
            vc.groupList = self.array;
            [self.navigationController pushViewController:vc animated:YES];
            vc.HomeDetailDeleteBlock = ^(NSString *groupId) {
                for (NSDictionary *dic in self.array) {
                    if ([dic[@"id"] integerValue]==groupId.integerValue) {
                        [self.array removeObject:dic];
                        break;
                    }
                }
                [self initView];
                [self getGroupList];
            };
            vc.HomeDetailAddBlock = ^{
                [self getGroupList];
            };
        }];
    }
}

@end
